<template>
  <el-tabs v-model="activeName" @tab-click="handleClick">
    <el-tab-pane label="其他座席" name="agent">
      <el-cascader
        ref="cascaderRef"
        style="width: 100%"
        popper-class="plus-popover"
        :options="agentOptions"
        placeholder="请输入名称或工号"
        filterable
      >
        <template #default="{ data }">
          <div v-if="data.freeNumber >= 0">
            <span>{{ data.label }}</span>
            <span>({{ data.freeNumber }})</span>
          </div>
          <div v-else class="clearfix" style="cursor: default" @click.stop>
            <span>{{ data.label }}</span>
            <span v-if="data.callStatusName">
              <span :class="data.callStatus === '0' ? 'free-status' : ''">{{
                data.callStatus === '0' ? '空闲' : '忙碌'
              }}</span></span
            >
            <span
              v-if="data.callStatus === '0'"
              :class="module === 'transfer' ? 'MC_icon-zhuanjie' : 'MC_icon-zixun'"
              class="MC_iconfont"
              @click.stop="transferAction(data.agentNumber, 'agent', data.label)"
            ></span>
          </div>
        </template>
      </el-cascader>
    </el-tab-pane>
    <el-tab-pane label="外线电话" name="outline">
      <el-input
        v-model="outlineNumber"
        size="mini"
        clearable
        placeholder="请输入手机或完整的区号电话号码"
        style="width: 244px"
      ></el-input>
      <el-button
        type="primary"
        size="default"
        class="action-btn"
        :disabled="!outlineNumber"
        @click.stop="transferAction(outlineNumber, 'outline', outlineNumber)"
        >{{ module === 'transfer' ? '转移' : '咨询' }}</el-button
      >
    </el-tab-pane>
    <el-tab-pane label="语音导航" name="ivr" v-if="module === 'transfer'">
      <el-select filterable v-model="ivrObj" value-key="nodeId" placeholder="请输入语音导航名字" style="width: 244px">
        <el-option v-for="item in ivrList" :key="item.nodeId" :label="item.name" :value="item" />
      </el-select>
      <el-button
        type="primary"
        size="default"
        class="action-btn"
        :disabled="!ivrObj.nodeId"
        @click.stop="transferAction(ivrObj.nodeId, 'ivr', ivrObj.name)"
        >转移</el-button
      >
    </el-tab-pane>
  </el-tabs>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, nextTick, ref, onBeforeMount } from 'vue'
import { geSdkIvrList, consult, transfer, geIdelAgent } from '@app/base/apis/call'
import { isNumber2 } from '@/common/utils/validate'
import { ElMessage } from 'element-plus'
import { userModule } from '@/common/store/modules/user'
export default defineComponent({
  name: 'transferConsult',
  components: {},
  props: {
    module: {
      type: String,
      default: ''
    }
  },
  setup(props, { emit }) {
    const cascaderRef: any = ref(null)
    const USERMODULE = userModule()
    const STATE: any = reactive({
      activeName: 'agent', // 当前tab选中项
      outlineNumber: '', // 当前填写的外线电话
      ivrList: [], // 语音导航的列表
      ivrObj: { name: '', nodeId: '' }, // 当前选中的语音导航
      agentOptions: []
    })
    // 触发转接或者咨询
    const transferAction = (number: string, mode: string, label: string) => {
      if (mode === 'outline') {
        // 转外线号码，校验号码
        if (!isNumber2(number) || !number) {
          // 不是纯数字 || 没有手机号
          ElMessage.error('请输入正确的号码')
          return false
        }
      }
      let action = consult
      const actionData: any = { number, mode }
      if (props.module === 'transfer') {
        action = transfer
      }
      action(actionData).then((res: any) => {
        if (res && res.success) {
          if (props.module === 'consult') {
            // 咨询请求成功，操作按钮变更咨询ing
            ElMessage.success('正在为您呼叫咨询中，请等待')
            // 把当前咨询的座席信息存储起来，咨询转移时用得上
            window.sessionStorage.setItem('currentConsultAgent', label)
          } else {
            ElMessage.success(`通话已转移至${label}`)
          }
        }
      })
      cascaderRef.dropDownVisible = false // 收起级联组件的面板
    }
    const fetchQueueOnlineAgents = () => {
      restFrom()
      geIdelAgent({}).then((res: any) => {
        if (res && res.success && res.data) {
          const dataList: any[] = []
          res.data.forEach((item: any) => {
            const itemObj: any = { value: item._id, label: item.name, freeNumber: 0 }
            let itemFreeNum = 0
            const agentArr: any = []
            if (item.members && item.members.length > 0) {
              item.members.forEach((item2: any) => {
                // 排除技能组内的自己（不能自己咨询或者是转移自己）
                if (item2.agentId !== USERMODULE.agent._id) {
                  const item2Obj: any = {
                    value: item2.agentId,
                    label: `${item2.agentName}[${item2.agentNumber}]`,
                    callStatus: item2.callStatus,
                    callStatusName: item2.callStatusName,
                    agentNumber: item2.agentNumber
                  }
                  if (item2.callStatus === '0') {
                    // 筛选出空闲的
                    itemFreeNum++
                  } else {
                    item2Obj.disabled = true
                  }
                  agentArr.push(item2Obj)
                } else {
                  // 匹配到是自己
                  if (item.members.length === 1) {
                    // 技能组内只有一个人，还是自己，disabled
                    itemObj.disabled = true
                  }
                }
              })
            } else {
              itemObj.disabled = true
            }
            itemObj.freeNumber = itemFreeNum
            if (agentArr.length > 0) {
              itemObj.children = agentArr
            }
            dataList.push(itemObj)
          })
          STATE.agentOptions = dataList
        }
      })
    }
    // 重置表单
    const restFrom = () => {
      STATE.outlineNumber = ''
      STATE.ivrObj = { name: '', nodeId: '' }
    }
    // tab切换
    const handleClick = () => {
      nextTick(() => {
        if (STATE.activeName === 'ivr') {
          // 每次tab切换过来的时候请求服务器的ivr列表 && 不需要遮罩
          geSdkIvrLists()
        } else if (STATE.activeName === 'agent') {
          fetchQueueOnlineAgents()
        }
      })
    }
    // 获取ivr列表
    const geSdkIvrLists = () => {
      geSdkIvrList({ hideLoading: true }).then((res: any) => {
        if (res.data) {
          STATE.ivrList = res.data || []
        }
      })
    }
    onBeforeMount(() => {
      fetchQueueOnlineAgents()
    })
    return {
      ...toRefs(STATE),
      fetchQueueOnlineAgents,
      handleClick,
      transferAction
    }
  }
})
</script>
<style scoped lang="stylus">
.free-status:before
  content ""
  display inline-block
  width 4px
  height 4px
  border-radius 50%
  margin 4px
  background-color var(--mc-success-color)
.MC_iconfont
   margin-left 10px
   cursor pointer
   color var(--mc-main-color)
.action-btn
  margin-left 6px
  vertical-align top
</style>
